<template>
  <!-- <div class="custom-calendar">
    <p>距离 {{ targetDateName }} 还有：</p>
    <p>
      {{ days }} 天 {{ hours }} 小时 {{ minutes }} 分 {{ seconds }} 秒！！！！
    </p>
  </div>
  <el-calendar ref="calendar">
    <template #date-cell="{ data }">
      <p>
        {{ data.day.split('-').slice(2).join('-').replace(/^0/, '') }}
      </p>
      <p style="font-size: 10px">
        {{ data.day == '2024-02-09' ? '除夕' : '' }}
        {{ data.day == '2024-02-10' ? '春节' : '' }}
        {{ data.day == '2024-02-02' ? '北方小年' : '' }}
        {{ data.day == '2024-02-03' ? '南方小年' : '' }}
      </p>
    </template>
  </el-calendar> -->
</template>

<script lang="ts">
import { ref } from 'vue'
import type { CalendarDateType, CalendarInstance } from 'element-plus'
export default {
  name: 'CountdownTimer',
  data() {
    return {
      targetDate: '2024-02-09T00:00:00', // 设置目标日期和时间
      targetDateName: '春节',
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      countdownInterval: null as any,
      calendar: ref<CalendarInstance>(),
    }
  },
  mounted() {
    // 在组件挂载后开始倒计时
    this.startCountdown()
  },
  beforeDestroy() {
    // 在组件销毁前清除定时器
    clearInterval(this.countdownInterval)
  },
  methods: {
    isCustomDate(
      row: { [x: string]: string },
      column: { key: string | number },
    ) {
      // 自定义判断是否为需要标记的日期，这里简单演示了一个条件
      return row[column.key] && row[column.key] === '2024-01-10'
    },
    selectDate(val: CalendarDateType) {
      if (!this.calendar) return
      this.calendar.selectDate(val)
    },

    startCountdown() {
      // 更新倒计时每秒钟
      this.countdownInterval = setInterval(() => {
        this.calculateTime()
      }, 1000)
    },
    calculateTime() {
      const now = new Date().getTime()
      const targetTime = new Date(this.targetDate).getTime()
      const timeDifference = targetTime - now

      if (timeDifference <= 0) {
        // 如果时间差小于等于零，说明已经到达目标日期，清除定时器
        clearInterval(this.countdownInterval)
      } else {
        // 计算剩余的天、小时、分钟和秒
        this.days = Math.floor(timeDifference / (1000 * 60 * 60 * 24))
        this.hours = Math.floor(
          (timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
        )
        this.minutes = Math.floor(
          (timeDifference % (1000 * 60 * 60)) / (1000 * 60),
        )
        this.seconds = Math.floor((timeDifference % (1000 * 60)) / 1000)
      }
    },
  },
}
</script>

<style scoped>
.custom-calendar {
  text-align: center;
}
</style>
